# -*- coding: utf-8 -*-
# !/usr/resources/python3

import re
import numpy
import json
import pypinyin
import yaml
import os
import uuid
import hashlib
import time


class Utility:
    @staticmethod
    def d2b(val):
        if val == 0:
            return '0'
        sign = ''
        if val < 0:
            val = -val
            sign = '-'
        b = ''
        while val != 0:
            b = str(val % 2) + b
            val = val // 2
        return sign + b

    @staticmethod
    def millisecond():
        return int(round(time.time() * 1000))

    @staticmethod
    def md5(text):
        md5 = hashlib.md5()
        md5.update(text.encode("utf-8"))
        return md5.hexdigest().lower()

    @staticmethod
    def file_md5(filename):
        m = hashlib.md5()  # 创建md5对象
        with open(filename, 'rb') as f:
            while True:
                data = f.read(4096)
                if not data:
                    break
                m.update(data)  # 更新md5对象
        md5 = m.hexdigest()  # md5
        del f, m
        return md5

    @staticmethod
    def config(key=None):
        file_name = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config.yaml').replace("\\", "/")
        data = yaml.load(open(file_name, 'r', encoding='UTF-8'), Loader=yaml.FullLoader)
        if key:
            return data[key]
        return data

    @staticmethod
    def array_format(obj):
        if isinstance(obj, (
                numpy.int_, numpy.intc, numpy.intp, numpy.int8, numpy.int16, numpy.int32, numpy.int64, numpy.uint8,
                numpy.uint16, numpy.uint32, numpy.uint64)):
            return int(obj)
        elif isinstance(obj, (numpy.float_, numpy.float16, numpy.float32,
                              numpy.float64)):
            return float(obj)
        elif isinstance(obj, (numpy.ndarray,)):  # add this line
            return obj.tolist()  # add this line
        return json.JSONEncoder.default(obj)

    # 名称转换
    @staticmethod
    def norm_name(words):
        # english special characters
        rep = {'ppT': 'ppt', 'pPt': 'ppt', 'pPT': 'ppt', 'Ppt': 'ppt', 'PpT': 'ppt', 'PPt': 'ppt'}
        rep = dict((re.escape(k), v) for k, v in rep.items())
        pattern = re.compile("|".join(rep.keys()))
        return pattern.sub(lambda m: rep[re.escape(m.group(0))], words)

    # 转拼音
    @staticmethod
    def pinyin(word):
        text = ''
        for i in pypinyin.pinyin(word, style=pypinyin.NORMAL):
            text += ''.join(i)
        return text

    # 词组
    @staticmethod
    def phrase(words):
        _result = []
        result = []
        for word in words:
            _result.append(word.upper())
        _result.extend(words)
        for item in _result:
            if item not in result:
                result.append(item)

        return result

    # 词组
    @staticmethod
    def stopped(word, dicts):
        for tag in dicts:
            word = word.replace(tag, '')

        return word

    # 填充 0
    @staticmethod
    def fill_zero(num, digit=3):
        zero = '00000000000000000000000000000000'
        num = str(num)
        return zero[0: digit - len(num)] + num

    # 字典合并
    @staticmethod
    def dict_merge(dict1, dict2):
        return {**dict1, **dict2}

    # url 检查
    @staticmethod
    def url_check(url):
        if re.match(r'^https?:/{2}\w.+$', url):
            return True
        else:
            return False

    # 取模
    @staticmethod
    def mod(a, b):
        c = a % b
        r = int((a - c) / b)
        return r

    # 取余
    @staticmethod
    def rem(a, b):
        c = int(a / b)
        r = a - c * b
        return r

    # 生成唯一码
    @staticmethod
    def make_code(key):
        chart = str(uuid.uuid4())
        chart = chart.replace(' ', '').replace('-', '')[:16]
        return str(key) + '_' + chart

    # 判断是否是中文
    @staticmethod
    def is_chinese(string):
        pattern = re.compile(r'[\u4e00-\u9fa5]+')
        result = re.match(pattern, string)
        if result:
            return True
        else:
            return False

    @staticmethod
    def seconds_to_hms(total_seconds):
        hours, remainder = divmod(total_seconds, 3600)
        minutes, seconds = divmod(remainder, 60)
        return f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}"
